package com.info33.platform.business.dialogue.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.business.dialogue.dao.AiTokenDao;
import com.info33.platform.business.dialogue.entity.AiToken;
import com.info33.platform.business.dialogue.service.AiTokenService;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.common.util.OKHttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @author LF
 * @date 2023-10-16 10:11:52
 */
@Service
public class AiTokenServiceImpl extends ServiceImpl<AiTokenDao, AiToken> implements AiTokenService {

    @Autowired
    private AiTokenDao aiTokenDao;

    @Value("${wenxin.api_key}")
    private String API_KEY;
    @Value("${wenxin.secret_key}")
    private String SECRET_KEY;

    @Override
    public Result<String> getToken() throws IOException {
        // 获取access_token(时效30天)
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;
        JSONObject params = new JSONObject();
        Map<String, Object> map = OKHttpUtil.dopost(url, params);
        if ("200".equals(map.get("status").toString())) {
            JSONObject accessTokenJSON = JSON.parseObject(map.get("result").toString());
            String accessToken = accessTokenJSON.get("access_token").toString();
            AiToken aiToken = new AiToken();
            aiToken.setToken(accessToken);
            if (save(aiToken)) {
                return Result.ok("成功!");
            }
        }
        return Result.error("失败!");
    }
}
